package com.example.shw

import android.content.Context
import android.graphics.Canvas
import android.graphics.drawable.AnimationDrawable
import android.media.MediaPlayer
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.view.MotionEvent
import android.view.View
import android.widget.FrameLayout
import android.widget.ImageView

class BoomActivity : AppCompatActivity(){
    private lateinit var myView: MyView
    private lateinit var anim: AnimationDrawable
    private lateinit var bomb: MediaPlayer

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val frame = FrameLayout(this)
        setContentView(frame)
        frame.setBackgroundResource(R.drawable.background)

        bomb = MediaPlayer.create(this, R.raw.enemy1_down)

        myView = MyView(this)
        myView.setBackgroundResource(R.drawable.blast)
        myView.visibility = View.INVISIBLE
        anim = myView.background as AnimationDrawable
        frame.addView(myView)
        frame.setOnTouchListener{ _, event ->
            if (event.action == MotionEvent.ACTION_DOWN)
            {
                anim.stop()
                val x = event.x
                val y = event.y
                myView.setLocation(y.toInt() - 40, x.toInt() - 20)
                myView.visibility = View.VISIBLE
                anim.start()
                bomb.start()
            }
            false
        }
    }

    internal inner class MyView(context: Context) : ImageView(context){
        fun setLocation(top: Int, left: Int){
            this.setFrame(left - 150, top - 150, left + 150, top + 150)
        }

        override fun onDraw(canvas: Canvas) {
            val field = AnimationDrawable::class.java.getDeclaredField("mCurFrame")
            field.isAccessible = true

            val curFrame = field.getInt(anim)

            if (curFrame == anim.numberOfFrames - 1)
            {
                visibility = View.INVISIBLE
            }
            super.onDraw(canvas)
        }
    }
}